import axios from "axios";
import localCache from "../../utils/cache";

import { BASE_URL } from "./origin";
import { ElLoading } from "element-plus";
import { ElMessage } from "element-plus";

import router from "@/router";

class LHRequest {
  constructor() {
    this.instance = axios.create({
      baseURL: BASE_URL, //'http://127.0.0.1:7001'
      timeout: 60000,
      withCredentials: true,
    });

    this.instance.interceptors.request.use(
      (config) => {
        ElLoading.service({
          lock: true,
          text: "Loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        const token = localCache.getCache("token");
        if (token) {
          config.headers["Authorization"] = "Bearer " + token;
        }
        return config;
      },
      (err) => {
        ElLoading.service().close();
        ElMessage.error({
          message: err,
        });
        console.log(err);
        return false;
      }
    );

    this.instance.interceptors.response.use(
      (result) => {
        ElLoading.service().close();
        if (result.data.statusCode) {
        }
        return result;
      },
      (err) => {
        console.log(err);
        ElLoading.service().close();
        ElMessage.error({
          message: err.response.data.msg,
        });
        if (err.response.data.code === 401) {
          router.push("/login");
        }
        return err;
      }
    );
  }

  request(config) {
    return new Promise((resovle, reject) => {
      this.instance
        .request(config)
        .then((res) => {
          resovle(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  get(config) {
    return this.request({ ...config, method: "GET" });
  }

  post(config) {
    return this.request({ ...config, method: "POST" });
  }

  update(config) {
    return this.update({ ...config, method: "UPDATE" });
  }

  delete(config) {
    return this.request({ ...config, method: "DELETE" });
  }
}

export default new LHRequest();
